import { AppstoreOutlined, SaveOutlined, UserOutlined } from '@ant-design/icons'
import { theme, Row, Col, Spin, Avatar, Button, message } from 'antd'
import {
  LoadingOutlined,
  ClearOutlined,
  PlusCircleOutlined,
  SendOutlined,
} from '@ant-design/icons'
import { useRef, useState } from 'react'
import type { Message } from '@/types/chat'
import { sendChat } from '@/services/chat'

function Empty() {
  return (
    <div className="h-full flex  items-center justify-center">
      <div className="text-center">
        <Avatar
          icon={<AppstoreOutlined />}
          size={70}
          style={{
            backgroundColor: '#87d068',
          }}
        />
        <p className="font-bold text-[28px] mt-2 leading-10">
          嗨，我能帮什么忙吗？
        </p>
      </div>
    </div>
  )
}
export default function AppDetail() {
  const {
    token: { colorFillContent, colorBgContainer },
  } = theme.useToken()
  const inputRef = useRef<HTMLInputElement>(null)
  // function autoResizeInput() {
  //   if (!inputRef.current) return
  //   inputRef.current.style.height = 'auto'
  //   if (inputRef.current.scrollHeight < 120) {
  //     inputRef.current.style.height = inputRef.current.scrollHeight + 'px'
  //   } else {
  //     inputRef.current.style.height = '120px'
  //   }
  //   inputRef.current.rows = inputRef.current.scrollHeight / 24
  // }
  const [loading, setLoading] = useState(false)
  const [messages, setMessages] = useState<Message[]>([])
  const [word, setWord] = useState('')
  function handleInput(e: React.ChangeEvent<HTMLInputElement>) {
    setWord(e.target.value)
  }
  function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    console.log(e.key)
    if (e.key === 'Enter') {
      handleSendMessage()
    }
  }
  async function handleSendMessage() {
    if (!word.trim()) {
      message.error('你还没有输入内容哦')
      inputRef.current?.focus()
      return
    }

    setMessages((prev) => [
      ...prev,
      {
        role: 'human',
        content: word,
      },
    ])
    setLoading(true)
    setWord('')
    try {
      const res = await sendChat(word)
      setLoading(false)

      if (res.code === 'success') {
        setMessages((prev) => [
          ...prev,
          {
            role: 'bot',
            content: res.data,
          },
        ])
      }
    } catch (e) {
      message.error('请求失败，请稍后再试')
      setLoading(false)
      return
    }
  }
  return (
    <div>
      <div
        className="h-[74px] flex"
        style={{
          background: colorFillContent,
        }}
      ></div>
      <div
        style={{
          background: colorBgContainer,
          height: 'calc(100vh - 74px)',
        }}
      >
        <Row className="h-full">
          <Col span={16}>
            <div className="h-[64px] text-xl flex items-center px-6">
              应用编排
            </div>
            <div className="flex">
              <div className="flex-1 px-6 text-sm font-bold">
                人设与回复逻辑
              </div>
              <div className="flex-1 px-6 text-sm font-bold">应用能力</div>
            </div>
          </Col>
          <Col span={8} className="flex flex-col h-full">
            <div className="h-[64px]  flex items-center px-4">
              <div className="flex-1 text-xl">预览与调试</div>
              <div className="text-blue-700">
                <SaveOutlined />
                <span className="ml-1">长期记忆</span>
              </div>
            </div>
            {messages.length === 0 ? (
              <Empty />
            ) : (
              <div className="flex-1 scrollbar-thumb-rounded-full scrollbar-track-rounded-full scrollbar scrollbar-thumb-gray-400 scrollbar-track-gray-300  overflow-y-auto scrollbar-w-[10px]">
                <div className="px-6 py-7 min-h-[100%]">
                  {messages.map((message) => {
                    return (
                      <div className="flex mb-6" key={message.content}>
                        {message.role === 'bot' ? (
                          <>
                            <div>
                              <Avatar
                                size={30}
                                style={{
                                  backgroundColor: '#87d068',
                                }}
                                icon={<AppstoreOutlined />}
                              />
                            </div>
                            <div className="flex-1 ml-[10px]">
                              <div className="text-sm font-bold">
                                ChatGPT 聊天机器人
                              </div>
                              <div className="px-4 py-3 mt-2 bg-gray-100 inline-block  rounded-xl	">
                                {!message.content && loading ? (
                                  <Spin indicator={<LoadingOutlined spin />} />
                                ) : (
                                  <>{message.content}</>
                                )}
                              </div>
                            </div>
                          </>
                        ) : (
                          <>
                            <Avatar
                              size={30}
                              style={{
                                backgroundColor: '#1677ff',
                              }}
                              icon={<UserOutlined />}
                            />
                            <div className="flex-1 ml-[10px]">
                              <div className="text-sm font-bold">用户</div>
                              <div className="px-4 py-3 mt-2 bg-blue-700 inline-block text-white rounded-xl	">
                                {message.content}
                              </div>
                            </div>
                          </>
                        )}
                      </div>
                    )
                  })}

                  {}
                  {loading && (
                    <div className="flex mb-6">
                      <div>
                        <Avatar
                          size={30}
                          style={{
                            backgroundColor: '#87d068',
                          }}
                          icon={<AppstoreOutlined />}
                        />
                      </div>
                      <div className="flex-1 ml-[10px]">
                        <div className="text-sm font-bold">
                          ChatGPT 聊天机器人
                        </div>
                        <div className="px-4 py-3 mt-2 bg-gray-100 inline-block  rounded-xl	">
                          <Spin indicator={<LoadingOutlined spin />} />
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}

            <div>
              <div className="flex items-center pr-9 pl-7">
                <Button
                  icon={<ClearOutlined />}
                  type="text"
                  className="text-gray-500 mr-2"
                />

                <div className="flex-1 box-border	 py-2 flex items-end border border-solid rounded-full border-gray-200 px-4 ">
                  {/* <textarea
                    className="outline-none border-none flex-1 self-center	 resize-none  min-h-[100%]	leading-6	"
                    ref={inputRef}
                    onInput={autoResizeInput}
                    rows={1}
                  /> */}
                  <div className="h-[34px] flex-1">
                    <input
                      className="outline-none h-full w-full"
                      value={word}
                      onInput={handleInput}
                      onKeyDown={handleKeyDown}
                      ref={inputRef}
                    />
                  </div>
                  <div>
                    <Button icon={<PlusCircleOutlined />} type="text" />

                    <Button
                      icon={<SendOutlined />}
                      type="text"
                      className="ml-1 text-blue-500 hover:text-blue-700"
                      loading={loading}
                      onClick={handleSendMessage}
                    />
                  </div>
                </div>
              </div>
              <p className="py-3 text-xs text-center text-gray-500">
                内容由AI生成，无法确保真实准确，仅供参考。
              </p>
            </div>
          </Col>
        </Row>
      </div>
    </div>
  )
}
